import { Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[ngxFor],[ngxId]',
})
export class NgxIdDirective {
  @Input('ngxFor') ngxFor?: any;

  constructor(private elRef: ElementRef, private renderer: Renderer2) {
  }

  ngOnInit(): void {
    if (!this.ngxFor)
      this.renderer.setAttribute(this.elRef.nativeElement, 'id', this.generateUUID());
  }

  ngAfterViewInit() {
    if (this.ngxFor)
      this.renderer.setAttribute(this.elRef.nativeElement, 'for', this.ngxFor.id);
  }

  private generateUUID(): string {
    let temp_url = URL.createObjectURL(new Blob());
    let uuid = temp_url.toString();
    URL.revokeObjectURL(temp_url);
    return uuid.substr(uuid.lastIndexOf('/') + 1);
  }
}
